const router = require('koa-router')()
const { sqlquery } = require('../APP/LK.js')
const axios = require('axios')
const md5 = require('md5')
const multer = require('koa-multer');

router.prefix('/users')

// ===================================================================== --已写
// 图片上传

//配置
var storage = multer.diskStorage({
  //文件保存路径
  destination: function (req, file, cb) {
    cb(null, "public/images/loutu/"); //注意路径必须存在
  },
  //修改文件名称
  filename: function (req, file, cb) {
    var fileFormat = file.originalname.split(".");
    cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
  },
});

//加载配置
var upload = multer({ storage: storage });

// 上传图片返回后缀名
router.post('/doAdd', upload.single('file'), async (ctx, next) => {
  ctx.body = { filename: ctx.req.file.filename }
});

// ===================================================================== 咱不用
// // 发布朋友圈
// router.get("/faPengYouQuan", upload.single("file"), async (ctx, next) => {
//   ctx.body = {
//     filename: ctx.req.file.filename, //返回文件名
//     body: ctx.req.body,
//   };
// });

// =====================================================================
// 根

router.get("/", function (ctx, next) {
  ctx.body = "这里是经纪人程序端";
});

// ===================================================================== --已写
// 经纪人登录接口

router.get("/admin", async function (ctx, next) {
  console.log("前台数据", ctx.query);
  let user = ctx.query.user; //用户名
  let pass = md5(ctx.query.pass); //密码
  let yzm = ctx.query.yzm; //验证码

  let sql = `select * from broker where phone='${user}' `;
  let res = await sqlquery(sql);
  console.log(res);

  // 先判断验证码是否正确
  // let authcode = ctx.session.authcode;//从本地获取session
  // console.log('本地session',authcode);
  // if( authcode == yzm){
  if (res.length > 0) {
    if (res[0].password == pass) {
      // 登录成功
      ctx.body = { code: 200, msg: "登录成功", data: res[0].phone, id: res[0].id };
    } else {
      ctx.body = { code: 203, msg: "密码错误", data: "" };
    }
  } else {
    ctx.body = { code: 202, msg: "用户名不存在", data: "" };
  }
  // }
  // else{
  //   ctx.body = {code:201,msg:'验证码错误！'}
  // }
});


// 随机数
function authcode() {
  var arr = "";
  for (var i = 0; i < 4; i++) {
    //从0-61之间取随机数
    var index = Math.floor(Math.random() * 10);
    arr += index;
  }
  return arr;
}

// ===================================================================== --已写
// 发送验证码

router.get("/authcode", async function (ctx, next) {
  let phone = ctx.query.phone;
  let yzm = authcode();
  console.log("验证码", yzm);
  console.log("手机号", phone);

  // var content = encodeURI('您的验证码是：' + yzm + '。请不要把验证码泄露给其他人。如非本人操作，可不用理会！')
  // var url = 'http://sms.106jiekou.com/utf8/sms.aspx?account=15833023881&password=15833023881&mobile=' + phone + '&content='+content
  // console.log(url)
  //  let res = await axios.get(url);//发送请求
  //   console.log(666,res.data);

  // if(res.data==100){
  // 存到本地session
  ctx.session.authcode = yzm;
  console.log("666session", ctx.session.authcode);
  ctx.body = {
    code: 200,
    msg: "发送成功",
  };
  // }
});

// ===================================================================== --已写
// 授权 用户信息入库  用户信息入库接口

router.get("/getUserInfo", async (ctx, next) => {
  let name = ctx.query.name; //微信昵称
  let img = ctx.query.img; //头像
  let code = ctx.query.code; //code
  let phone = ctx.query.phone; //电话

  let AppID = "wx1bc62c2d63f12168";
  let AppSecret = "b1280e33fd3e7f1a53878aaf64199359";
  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${AppID}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code`;
  // 发送请求
  let data = await axios.get(url);
  console.log(1818, data.data); //返回openid

  let openid = data.data.openid;
  let json = {};

  // 查
  let user = await deng(openid);
  if (user) {
    json = {
      code: 200,
      msg: "登录成功",
      data: user
    };
  } else {
    await zhuce(name, img, openid, phone);
    let user = await deng(openid);
    json = {
      code: 206,
      msg: "注册并登录成功",
      data: user
    };
  }

  ctx.body = json;
});

// 查询
async function deng(openid) {
  let sql = `select * from broker where openid='${openid}'`;
  let res = await sqlquery(sql);
  return res[0].openid;
}

// 修改
async function zhuce(name, img, openid, phone) {
  let sql = `update broker set username='${name}',img='${img}',openid='${openid}' where phone='${phone}'`;
  await sqlquery(sql);
}

// ===================================================================== -- 已写
//获取经纪人房源
router.get("/getbrokerlist", async function (ctx, next) {
  let openid = ctx.query.openid;

  let sql = `SELECT
	b.id,b.openid,b.username,b.img, 
	count(CASE WHEN h.state = 1 THEN h.state ELSE null END) AS state1,
		count(CASE WHEN h.state = 2 THEN h.state ELSE null END) AS state2,
		count(CASE WHEN h.state = 3 THEN h.state ELSE null END) AS state3
	FROM
	broker b
	JOIN houses h ON b.id = h.broker_id WHERE b.openid = '${openid}'
	GROUP BY b.id`;

  let res = await sqlquery(sql);
  console.log(666, res);
  ctx.body = {
    code: "200",
    msg: "查询成功",
    data: res[0],
  };
});

// ===================================================================== --已写
//获取楼市圈数据
router.get('/getLouSHI', async function (ctx, next) {
  let sql = `SELECT a.id,a.yue,a.yueri,a.content,a.broker_id,c.name,c.img headimg,b.img FROM building_circle a left JOIN broker c on c.id=a.broker_id left JOIN building_circle_img b on a.id = b.key_id ORDER BY a.id desc`;
  let res = await sqlquery(sql);
  var map = {}
  res.forEach(function (item) {
    console.log(item.id)
    map[item.id] = item
  })
  res.forEach(function (item) {
    if (map[item.id] && item.img) {
      (map[item.id].children || (map[item.id].children = [])).push(item.img)
    }
  });

  console.log(213, map)
 
   // 对象转数组并倒序
  function objToArray(array) {
    let arr = [];
    for (var i in array) {
    let item = array[i]
    arr.push(item);
    };
    return arr.reverse();
  }

  map = objToArray(map);//把对象处理成数组后重新赋值返回

  console.log(217, map)

  ctx.body = {
    code: '200',
    msg: '楼市圈列表查询成功',
    data: map
  }

})

// ===================================================================== ----已写
//添加一条楼市圈信息
router.get('/addONElsq', async function (ctx, next) {
  console.log('添加楼市圈参数', ctx.query);

  let content = ctx.query.content;
  let id = ctx.query.id;
  let filename = ctx.query.filename;
  let imgurl = '/images/loutu/' + filename;


  // 日期
  var myDate = new Date();
  var yue = myDate.getMonth() + 1;//当前月份
  var yueri = yue + '/' + myDate.getDate();//获取当前日(1-31)

  let sql = `insert into building_circle values (null,'${yue}','${yueri}','${content}','${id}')`;
  let res = await sqlquery(sql)
  console.log(res);

  let sqls = `insert into building_circle_img values (null,'${imgurl}','${res.insertId}')`;
  await sqlquery(sqls)

  ctx.body = {
    code: 200,
    msg: '添加成功'
  }

})


// =====================================================================
//删除楼市圈
router.get('/delPYQ', async function (ctx, next) {
  console.log('删除楼市圈接口参数', ctx.query);
  let id = ctx.query.id;
  let sql = `delete from building_circle where id='${id}'`;
  let res = await sqlquery(sql);
  console.log(res);
  ctx.body = {
    code: 206,
    msg: '删除成功'
  }
})


// =====================================================================
//获取房源、新房、二手房、租房
router.get('/getBrokerXin', async function (ctx, next) {
  let page = ctx.query.page;//1
  let limit = ctx.query.limit;//5
  console.log('获取新房接口参数', ctx.query);
  let id = ctx.query.id;//经纪人id
  let state = ctx.query.state;//类型
  let area = ctx.query.area;//区域
  let slider = ctx.query.slider;//价格
  let deploy = ctx.query.deploy;//户型

  let sql = `select * from houses where broker_id='${id}' and state='${state}'`
  if (area) {//地区
    sql += ` and district = '${area}' `
  }
  if (slider) {//价格
    sql += ` and price <= '${slider}' `
  }
  if (deploy) {//户型
    sql += ` and deploy = '${deploy}' `
  }

  //分页查询 (1-1)*5,5=0,5  (2-1)*5,5=5,5 (3-1)*5,5=10,5
  sql += ` limit ${(page - 1) * limit},${limit}`;

  console.log(sql)
  let res = await sqlquery(sql);

  console.log('获取新房查询结果', res);
  ctx.body = {
    code: 200,
    msg: '查询成功',
    data: res
  }
})

// ===================================================================== --已写
//区域筛选列表渲染
router.get('/getDistrict', async function (ctx, next) {
  let sql = `select * from district`
  let res = await sqlquery(sql);
  ctx.body = {
    code: 200,
    msg: '查询成功',
    data: res
  }
})

// =====================================================================
//操作团购信息
router.get('/getKaiTuan', async function (ctx, next) {
  let state = ctx.query.state;
  let id = ctx.query.id;
  let sql = `select * from group_purchase `
  if (state && id) {//如果有状态进来就修改开启和关闭的子段
    sql = `update group_purchase set buy_state = '${state}' where id = ${id} `
  } else if (id) {
    sql = `delete from group_purchase where id = ${id} `
  }
  console.log('330开团sql', sql);
  let res = await sqlquery(sql);
  console.log(329, res);
  ctx.body = {
    code: 200,
    msg: '开团查询成功',
    data: res
  }
})

// =====================================================================
//创建团购信息
router.get('/AddCreateTGo', async function (ctx, next) {
  console.log(ctx.query);
  let title = ctx.query.title;
  let dizhi = ctx.query.dizhi;
  let ktime = ctx.query.ktime;
  let jtime = ctx.query.jtime;
  let jieshao = ctx.query.jieshao;
  let filename = '/images/loutu/' + ctx.query.filename;

  let sql = `insert into group_purchase VALUES (null,'${filename}','${title}','${dizhi}','${ktime}','${jtime}','${jieshao}',null,null,null,2,null,null);`

  console.log(349, sql);

  let res = await sqlquery(sql);
  console.log(351, res);
  ctx.body = {
    code: 200,
    msg: '创建开团成功'
  }
})

// =====================================================================
//修改团购信息
router.get('/UpKaiTuanl', async function (ctx, next) {
  console.log(ctx.query);
  let jihe = ctx.query.jihe;
  let dizhi = ctx.query.dizhi;
  let shepai = ctx.query.shepai;
  let id = ctx.query.id;

  let sql = `update group_purchase set gather_site='${dizhi}',cpn='${shepai}',gather_time='${jihe}' where id='${id}'`;
  console.log(371, sql);
  await sqlquery(sql);
  ctx.body = {
    code: 200,
    msg: '修改成功'
  }
});

// =====================================================================
//根据id查询开团
router.get('/GetKaiTuanOne', async function (ctx, next) {
  let sql = `select * from group_purchase`
  let res = await sqlquery(sql);
  ctx.body = {
    code: 200,
    msg: '查询成功',
    data: res[0]
  }
})


// =====================================================================
//查询排行榜接口
router.get('/getPaiHangBang', async function (ctx, next) {
  let sql = `select b.name,b.company,b.img,c.company_name from broker b JOIN company c on b.company=c.id`
  let res = await sqlquery(sql);
  ctx.body = {
    code: 200,
    msg: '查询成功',
    data: res
  }
})

// =====================================================================
//获取所有房源表信息
router.get('/getHousersInFor', async function (ctx, next) {
  let sql = `select * from houses WHERE latitude != ''a nd longitude != ''`
  let res = await sqlquery(sql);
  console.log(334, res);
  ctx.body = {
    code: 200,
    msg: '开团查询成功',
    data: res
  }
})

// =====================================================================
//查询求租和求购接口
router.get('/getQiuzu', async function (ctx, next) {
  console.log(ctx.query);
  let state = ctx.query.state;
  let sql = 'SELECT * FROM `seek` where state=' + state
  let res = await sqlquery(sql);
  ctx.body = {
    code: 200,
    msg: '查询成功',
    data: res
  }
})

// =====================================================================
//查询公告
router.get('/GetGOnggao', async function (ctx, next) {
  let sql = 'SELECT * FROM `gonggao`'
  let res = await sqlquery(sql);
  ctx.body = {
    code: 200,
    msg: '查询成功',
    data: res
  }
})


// =====================================================================

module.exports = router
